/**
 * @class Spark.DatePicker
 * @extends Spark.TriggerField
 * <p>DatePicker组件.
 * @author njq.niu@hand-china.com
 * @constructor
 * @param {Object} config 配置对象. 
 */
$S.DatePicker = Ext.extend($S.TriggerField,{
	constructor: function(config) {
        this.dateFields = [];
        $S.DatePicker.superclass.constructor.call(this,config);
    },
    initComponent : function(config){ 
        $S.DatePicker.superclass.initComponent.call(this,config);
        this.initFormat();
        this.initFooter();
    },
    initFooter : function(){},//TODO: today button?
    initFormat : function(){
        this.format=this.format||$S.defaultDateFormat;
    },
    initDateField:function(){
    	if(this.inited) return;
    	this.inited = true;
    	this.size=this.size||1;
        this.popup.setStyle('width',(180*this.size + 4 + (this.size-1)*2)+"px");
    	var t =  this.getValue() || new Date();
    	var y = t.getFullYear();
    	var m = t.getMonth();
    	if(this.dateFields.length==0){
    		for(var i=0;i<this.size;i++){
    			var p = i==0,n = i==(this.size-1);
                var cfg = {
                    id:this.id+'_df'+i,
                    width:180,
                    showPreBtn:p,
                    showNextBtn:n,
                    height:158,
                    sbg:true,
                    className:"s_df",
                    initDate:new Date(y, m, 1),
                    listeners:{
                    	'select':this.onSelect.createDelegate(this),
                    	'pre':this.onPre.createDelegate(this),
                    	'next':this.onNext.createDelegate(this),
                    	'over':this.onOver.createDelegate(this),
                        "mouseover":this.mouseOver.createDelegate(this)
                    }
                }
    			this.dateFields.push(new $S.DateField(cfg));
    			m++;
    		}
    	}
        this.focusField = this.dateFields[0];
//    	this.shadow.setWidth(this.popup.getWidth()).setHeight(this.popup.getHeight());
    },
    initEvents : function(){
    	$S.DatePicker.superclass.initEvents.call(this);
        this.addEvents(
        /**
         * @event select
         * 选择事件.
         * @param {Spark.DatePicker} datePicker 日期选择组件.
         * @param {Date} date 选择的日期.
         */
        'select');
    },
    mouseOver: function(c,e){
        this.focusField = c
    },
    onKeyDown: function(e){
        if(this.disabled) return;
        if(this.isExpanded){
            var kc = e.keyCode;
            switch(kc){
                case 37:this.goLeft(e);break;
                case 38:this.goUp(e);break;
                case 39:this.goRight(e);break;
                case 40:this.goDown(e);break;
                case 33:this.focusField.preMonth();break;
                case 34:this.focusField.nextMonth();break;
                case 13:this.focusField.selectTarget(this.focusField.overTd);
            }
        }
        $S.DatePicker.superclass.onKeyDown.call(this,e);
    },
    getFieldOverTd : function(){
        var ff = this.focusField;
        if(!ff.overTd){
            if(ff.sd)ff.overTd = ff.cache['_'+ff.sd.getTime()]
            if(!ff.overTd)ff.focusDate(ff.tbody.first().child('td.s_day').dom);        
        }
        return ff.overTd;
    },
    goLeft : function(e){
        var field = this.focusField,fs = this.dateFields;
        var td = this.getFieldOverTd(),prev = Ext.fly(td).prev('.s_day'),parent = Ext.fly(td).parent(),r = parent.getAttributeNS('','_r');
        if(prev)field.focusDate(prev);
        else{
            var f = fs[fs.indexOf(field)-1];
            if(f)this.focusField = f;
            else{
                field.preMonth();
                this.focusField = fs[fs.length-1];
            }
            var l = this.focusField.tbody.child('tr[_r='+r+']').select('td.s_day');
            this.focusField.focusDate(l.item(l.getCount()-1).dom);
        }
        e.stopEvent();
    },
    goRight : function(e){
        var field = this.focusField,fs = this.dateFields;
        var td = this.getFieldOverTd(),next = Ext.fly(td).next('.s_day'),parent = Ext.fly(td).parent(),r = parent.getAttributeNS('','_r');;
        if(next) field.focusDate(next);
        else{
            var f = fs[fs.indexOf(field)+1];
            if(f)this.focusField = f;
            else{
                field.nextMonth();
                this.focusField = fs[0];
            }
            this.focusField.focusDate(this.focusField.tbody.child('tr[_r='+r+']').child('td.s_day').dom);
        }
        e.stopEvent();
    },    
    goUp : function(e){
        var field = this.focusField,fs = this.dateFields,
            td = this.getFieldOverTd(),prev = Ext.fly(td).parent().prev(),
            index = Ext.fly(td).getAttributeNS('','_c'),t;
        if(prev)t = prev.child('td[_c='+index+']').dom;
        if(t)field.focusDate(t);
        else {
            field.preMonth(this.size);
            var l = this.focusField.tbody.select('td[_c='+index+']');
            this.focusField.focusDate(l.item(l.getCount()-1).dom);
        }
    },
    goDown : function(e){
        var field = this.focusField,fs = this.dateFields,
            td = this.getFieldOverTd(),next = Ext.fly(td).parent().next(),
            index = Ext.fly(td).getAttributeNS('','_c'),t;
        if(next)t = next.child('td[_c='+index+']').dom;
        if(t)field.focusDate(t);
        else {
            field.nextMonth(this.size);
            this.focusField.focusDate(this.focusField.tbody.child('td[_c='+index+']').dom);
        }
    },
    onKeyUp: function(e){
        if(this.disabled)return;
    	$S.DatePicker.superclass.onKeyUp.call(this,e);
        var c = e.keyCode;
        if(!e.isSpecialKey()){
        	try{
        		var td = this.getRawValue().parseDate(this.format);
                this.wrapDate(td);
                this.predraw(td)
        	}catch(e){}
        }
    },
    selectDate : function(date){
        this.collapse();
        this.processDate(date);
        this.setValue(date);
        this.fireEvent('select',this, date);
        this.focus();
    },
    onSelect : function(field, date){
    	Ext.each(this.dateFields, function(df){
            if(df != field) df.unselect(df.sd);
        })
        this.selectDate(date);
    },
    wrapDate : function(d){},
    processDate : function(d){},
    onPre : function(field,prev){
        Ext.each(this.dateFields, function(df){
            if(df != field) {
                df.sd = field.sd;
                df.preMonth(prev,false);
            }
        })
//        this.focusField = null;
    },
    onNext : function(field,next){
        Ext.each(this.dateFields, function(df){
            if(df != field) {
            	df.sd = field.sd;
                df.nextMonth(next, false);         
            }
        })
//        this.focusField = null;
    },
    onOver : function(field){
        Ext.each(this.dateFields, function(df){
            if(df != field && df.overTd) Ext.fly(df.overTd).removeClass('over');        
        })
    },
    processValue : function(rv){
        if(Ext.isEmpty(rv)){
            return null;
        }else {
            try{
                var pd = rv.parseDate(this.format);
                this.wrapDate(pd)
                return pd;
            }catch(e){
                $S.showErrorMessage("错误","日期格式不正确!");
                return null;
            }
        }
    },
    formatValue : function(date){
    	if(date instanceof Date)return date.format(this.format);
    	return date;
    },
    doExpand : function(){
    	this.initDateField();
    	var v = this.getValue()
        if(!Ext.isEmpty(v)) {
        	this.predraw(v)
        }
    	$S.DatePicker.superclass.doExpand.call(this);
    },
    collapse : function(){
        $S.DatePicker.superclass.collapse.call(this);
        if(this.focusField)this.focusField.blurDate();
//        this.focusField = null;
    },
    predraw : function(v){
        if(v){
            var y = v.getFullYear(), m = v.getMonth(),cf = this.dateFields[0];
            cf.sd = v;
            cf.predraw(v);
            Ext.each(this.dateFields, function(df){
                if(df != cf) {
                    df.sd = v; 
                    df.predraw(new Date(y, ++m, 1));
                }
            })
        }
    },
    destroy : function(){
    	$S.DatePicker.superclass.destroy.call(this);
	}
});